﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using log4net;

namespace DC2010.Logic
{
    public class Serializer<T>
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Serializer<T>));

        public static void Serialize(string FileName, T input)
        {
            try
            {
                XmlSerializer s = new XmlSerializer(typeof(T));
                TextWriter w = new StreamWriter(FileName);

                s.Serialize(w, input);
                w.Close();
            }
            catch (Exception ex)
            {
                Logger.Error("Core, Serialize", ex);
            }
        }

        public static T Deserialize(string FileName)
        {
            T retval;

            try
            {
                XmlSerializer s = new XmlSerializer(typeof(T));
                if (!File.Exists(FileName))
                {
                    Logger.ErrorFormat("Core, File {0} not loaded.", FileName);
                    return default(T);
                }

                TextReader r = new StreamReader(FileName);

                retval = (T)s.Deserialize(r);
                r.Close();

                return retval;
            }
            catch (Exception ex)
            {
                Logger.Error("Core, Serialize", ex);
            }

            return default(T);
        }

    }
}
